<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;

class SqlListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param QueryExecuted $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        if (config('app.debug')) {
            $sql = str_replace('%', '%%', $event->sql);
            $sql = str_replace('?', '%s', $sql);
            $bindings = [];
            foreach ($event->bindings as $key => $value) {
                if (is_string($value)) {
                    $value = "'" . addslashes($value) . "'";
                } elseif (is_bool($value)) {
                    $value = $value ? 'true' : 'false';
                } elseif (is_null($value)) {
                    $value = 'null';
                }
                if (is_numeric($key)) {
                    $bindings[] = $value;
                } else {
                    $sql = str_replace(':' . $key, $value, $sql);
                }
            }
            $sql = vsprintf($sql, $bindings);
            $time = $event->time;
            $method = request()->getMethod();
            $uri = request()->getRequestUri();
            $date = date('Y-m-d H:i:s');
            $message = "[$date] {$method} {$uri}\nexecution time: {$time}ms;\n{$sql};\n\n";
            file_put_contents(storage_path('logs/sql.log'), $message, FILE_APPEND);
        }
    }
}
